
CDR.Constant.WINDOW_EDIT_MODE = 'edit';
CDR.Constant.WINDOW_NEW_MODE = 'new';
//create new win
var siteWindown = Ext.create('widget.window', {
	title: CDR.I18N['organization.tree.new'],
	closable: true,
	closeAction: 'hide',
	width: 375,
	height: 200,
	bodyStyle: 'padding: 5px;',
	mode: 'new',
	targetObject : {},
	initState: function (obj) {
		this.down('form').getForm().reset();
		this.targetObject = obj;
		this.mode = CDR.Constant.WINDOW_NEW_MODE;
		this.down('button').setText("Add");
	},
	editState: function (obj) {
		this.initState(obj);
		this.mode = CDR.Constant.WINDOW_EDIT_MODE;
		//fill data
		var node = this.targetObject.me.getSelectedNode();
		this.targetObject.node = node;
		this.down('hidden').setValue(node.getId());
		this.down('textfield').setValue(node.data.name);
		this.down('textareafield').setValue(node.data.description);
		this.down('button').setText("Update");
	},
	items: [{
		xtype: 'form',
		url:'create-site',
		items:[{
			xtype: 'textfield',
			allowBlank: false,
			fieldLabel: 'Name',
			width:350,
			name: 'name',
			validateOnBlur: true,
			textValid: true,
			textError: '',
			listeners: {
				'blur': function(textfield) {
					var winInit = this.up('window');
					var val = textfield.getValue();
					if(Ext.String.trim(val) != ''){
						if(winInit.mode === CDR.Constant.WINDOW_NEW_MODE) {
							Ext.Ajax.request({
								scope: textfield,
								async: false,
								url: 'check-site-name?value=' + val,
								success: function(response, opts) {
									var obj = Ext.decode(response.responseText);
									if(obj.success) {
										this.clearInvalid();
										this.textValid = true;
									}else {
										this.textError = obj.msg;
										this.textValid = false;
									}
								},
								failure: function(response, opts) {
									var obj = Ext.decode(response.responseText);
									this.textError = obj.msg;
									this.textValid = false;
								}
							});	
						} else if (winInit.mode === CDR.Constant.WINDOW_EDIT_MODE) {
							var originText = winInit.targetObject.node.data.name;
							if (originText != val) {
								Ext.Ajax.request({
									scope: textfield,
									async: false,
									url: 'check-site-name?value=' + val,
									success: function(response, opts) {
										var obj = Ext.decode(response.responseText);
										if(obj.success) {
											this.clearInvalid();
											this.textValid = true;
										}else {
											this.textError = obj.msg;
											this.textValid = false;
										}
									},
									failure: function(response, opts) {
										var obj = Ext.decode(response.responseText);
										this.textError = obj.msg;
										this.textValid = false;
									}
								});	
							}
						} else {
							this.textValid = true;
						}
					}
					this.validate();
				}
			},
			validator: function () {
				return this.textValid ? this.textValid : this.textError;
			}
		},{
			xtype: 'hidden',
			name: 'id'
		},{
			xtype: 'hidden',
			name: 'mode'
		}, {
			xtype: 'textareafield',
			allowBlank: false,
			fieldLabel: 'Description',
			width:350,
			name: 'description'
		}],
		buttons: [{
			text: 'Add',
			formBind: true, 
			handler: function() {
				var me = this.up('window');
				var form = this.up('form').getForm();
				if (form.isValid()) {
					if(me.mode == CDR.Constant.WINDOW_EDIT_MODE){
						var slNode = me.targetObject.me.getSelectedNode();
						this.up('form').down('hidden[name=id]').setValue(slNode.getId());
						this.up('form').down('hidden[name=mode]').setValue(CDR.Constant.WINDOW_EDIT_MODE);
						form.submit({
							success: function(form, action) {
							   Ext.Msg.alert('Success', action.result.msg);
							   me.hide();
							   if(me.targetObject.kind === CDR.widget.Site.NODE_SITE ) {
									var data = form.getValues();
									me.targetObject.me.updateNode(data, false);
								} 
							},
							failure: function(form, action) {
								Ext.Msg.alert('Failed', action.result.msg);
							}
						});
					} else {
						var slNode = me.targetObject.me.getSelectedNode();
						this.up('form').down('hidden[name=id]').setValue(slNode.getId());
						this.up('form').down('hidden[name=mode]').setValue(CDR.Constant.WINDOW_NEW_MODE);
						form.submit({
							success: function(form, action) {
							   Ext.Msg.alert('Success', action.result.msg);
							   me.hide();
							   if(me.targetObject.kind === CDR.widget.Site.NODE_SITE ) {
									var data = form.getValues();
									data.id = action.result.id;
									me.targetObject.me.addNode(data, false);
								} 
							},
							failure: function(form, action) {
								Ext.Msg.alert('Failed', action.result.msg);
							}
						});
					}
				}
			}
		},{
			text: 'Cancel',
			handler: function() {
				this.up('window').hide();
			}
			
		}]
	}]
});


//create tree widget for site
Ext.define('CDR.widget.SiteTree', {
  extend: 'Ext.tree.Panel',
  alias : 'widget.sitetree',
  title: CDR.I18N['organization.tree.title'],
  rootVisible: true,
  displayField: 'name',
  initComponent: function() {
	  var me = this;
	 
      this.count = 1;
      /*this.tbar = [{
          xtype: 'textfield',
          fieldLabel: 'Filter',
          labelWidth: 45,
			listeners: {
				'change': function(els, newVal, oldVal){
					//console.log(me.store);
					//me.store.clearFilter();
					/*me.store.filterBy(function(rec, id){
				         console.log(rec);
				         //return (rec.store("text") == selection.data.text);
				    });
				}
			}
      }];*/
      
      this.store = Ext.create('Ext.data.TreeStore', {
			 proxy: {
				type: 'ajax',
				url: 'tree-view'
			},
          fields: ['id','name','description'],
          root: CDR.rootNode
      });
      
      
      this.menu = Ext.createWidget('menu',{
			items:[{
					text: CDR.I18N['organization.tree.new'],
					iconCls:'icon-add',
					handler: function() {
						siteWindown.initState({'me': me, kind: CDR.widget.Site.NODE_SITE});
						siteWindown.show();
					}
				}, {
					text: CDR.I18N['organization.tree.edit'],
					iconCls:'icon-edit',
					handler: function() {
						siteWindown.editState({'me': me, kind: CDR.widget.Site.NODE_SITE});
						siteWindown.show();
					},
					scope: this
				}, {
					text: CDR.I18N['organization.tree.delete'],
					iconCls:'icon-delete',
					handler: function() {
						this.removeNode();
					},
					scope: this
			}]
      });
      me.callParent();
  },
  listeners: {
		render: function() {
			 Ext.getBody().on("contextmenu", Ext.emptyFn,
				null, {preventDefault: true});
      },
		itemcontextmenu:function(el, r, node, index, e, eOpts){
			el.select(r);
			this.menu.showAt(e.xy);
		}, 
		itemclick: function(el, r) {
			var id = r.getId();
			this.userView.store.setProxy({
              type: 'ajax',
              url : 'pbx-user-view?parentId=' + id,
              reader: {
                  type: 'json',
                  root: 'results'
              }
          });
			this.userView.store.load({scope : this,
				callback: function(rs, operation, success) {
					Ext.each(rs, function(r){
						if(r.data.type == "USER" && r.data.admin == true){
							this.userView.adminUser = r;
						}
					},this);
			}});
		}
      
	},
	getSelectedNode : function(){
		return this.getSelectionModel().getLastSelected();
	},
	reloadSelectedNode: function(){
		var node = this.getSelectionModel().getLastSelected();
		if (!this.store.clearOnLoad) {
			node.removeAll();
		}
		this.store.load({
		    node: node
		});
	},
	reloadSameItemClick: function(idOb){
		var id;
		if(idOb) {
			id = idOb;
		} else {
			var node = this.getSelectionModel().getLastSelected();
			id = node.getId();
		}
		this.userView.store.setProxy({
            type: 'ajax',
            url : 'pbx-user-view?parentId=' + id,
            reader: {
                type: 'json',
                root: 'results'
            }
        });
		this.userView.store.load({scope : this,
			callback: function(rs, operation, success) {
				Ext.each(rs, function(r){
					if(r.data.type == "USER" && r.data.admin == true){
						this.userView.adminUser = r;
					}
				},this);
		}});
	},
	/**
	 * Adds a new album node to the root
	 */
	addNode: function(data, leaf) {
		var selectednode = this.getSelectionModel().getLastSelected();
		selectednode.appendChild({id: data.id, name:data.name, description: data.description, leaf:leaf});
	},
	updateNode: function(data) {
		var selectednode = this.getSelectionModel().getLastSelected();
		selectednode.set('name', data.name);
		console.log(selectednode);
		selectednode.data.description = data.description;
    },
	removeNode: function(){
		var selectednode = this.getSelectionModel().getLastSelected();
		selectednode.remove(true);
	}
});
